package servlet;

import util.ParameterUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Arrays;

/**
 * @author 黄衡熙
 * @version 1.0
 */
@WebServlet("/modifyEmp")
public class ModifyEmpServlet extends HttpServlet {
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        String id=req.getParameter("id");
        String name = req.getParameter("name");
        String salary=req.getParameter("salary");
        String gender=req.getParameter("gender");
        String edu=req.getParameter("edu");
        String[] hobbies=req.getParameterValues("hobbies");
        Connection conn=null;
        PreparedStatement ps=null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8","root","qq670892");
            String sql = new StringBuffer()
                    .append(" update t_emp ")
                    .append(" set ")
                    .append(" name=?, ")
                    .append(" salary=?, ")
                    .append(" gender=?, ")
                    .append(" edu=?, ")
                    .append(" hobbies=? ")
                    .append(" where id=? ")
                    .toString();
            ps=conn.prepareStatement(sql);
            ps.setString(1,name);
            ps.setDouble(2, Double.parseDouble(salary));
            ps.setString(3,gender);
            ps.setString(4,edu);
            ps.setString(5,ParameterUtil.arrayToString(hobbies));
            ps.setInt(6,Integer.parseInt(id));
            ps.executeUpdate();
            req.getRequestDispatcher("findAll").forward(req,resp);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
